<?php

namespace App\Models\ReportForms;

use App\Models\Order\Outboundorder;
use App\Models\Order\Saleorder;
use App\Models\Order\Salesorder;
use App\Models\Purchase\PurchaseSettlePriceLog;
use App\Models\Purchase\PurchaseStockinOrder;
use App\Models\Purchase\PurchaseWarehousingOrder;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Saleprice\Saleprice;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ReportForms extends Model
{
    protected $table = 'report_forms';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    private const QUERY_CONFIG = [
        // 出库量
        1 => [
            'model' => Outboundorder::class,
            'relation' => 'outbound_order_sub',
            'time_field' => 'outbound_order.create_at',
            'value_field' => 'weight',
            'sum_field' => 'total_weight',
            'join_condition1' => 'outbound_order_sub.p_id',
            'join_condition2' => 'outbound_order.id',
            'cpid_field' => 'outbound_order.cpid',
            'group_relations' => [
                1 => 'outbound_order.manger_id',
                2 => 'outbound_order_sub.steel_factory_name',
                3 => 'outbound_order.custom_id',
                4 => 'outbound_order_sub.archive_material',
                5 => 'outbound_order_sub.archive_spec'
            ]
        ],
        // 入库量
        2 => [
            'model' => PurchaseWarehousingOrder::class,
            'relation' => 'purchase_warehousing_order_sub',
            'time_field' => 'purchase_warehousing_order.audit_at',
            'value_field' => 'total_weight',
            'sum_field' => 'total_weight',
            'join_condition1' => 'purchase_warehousing_order_sub.warehousing_order_id',
            'join_condition2' => 'purchase_warehousing_order.id',
            'cpid_field' => 'purchase_warehousing_order.cpid',
            'conditions' => [
                'purchase_warehousing_order.is_del' => 1,
                'purchase_warehousing_order.audit_status' => 3
            ],
            'group_relations' => [
                1 => 'purchase_warehousing_order.manger_id',
                2 => 'purchase_warehousing_order_sub.steel_factory_name',
                3 => 'purchase_warehousing_order.custom_id',
                4 => 'purchase_warehousing_order_sub.archive_material',
                5 => 'purchase_warehousing_order_sub.archive_spec'
            ]
        ],
        // 销售业绩
        3 => [
            'model' => Outboundorder::class,
            'relation' => 'outbound_order_sub',
            'time_field' => 'outbound_order.create_at',
            'value_field' => 'performance',
            'sum_field' => 'total_performance',
            'join_condition1' => 'outbound_order_sub.p_id',
            'join_condition2' => 'outbound_order.id',
            'cpid_field' => 'outbound_order.cpid',
            'group_relations' => [
                1 => 'outbound_order.manger_id',
                2 => 'outbound_order_sub.steel_factory_name',
                3 => 'outbound_order.custom_id',
                4 => 'outbound_order_sub.archive_material',
                5 => 'outbound_order_sub.archive_spec'
            ]
        ],
        // 销售毛利
        4 => [
            'model' => Outboundorder::class,
            'relation' => 'tplus_sale_gross_profit_analysis_summary',
            'time_field' => 'tplus_sale_gross_profit_analysis_summary.voucher_time',
            'value_field' => 'gross_profit',
            'sum_field' => 'total_gross_profit',
            'join_condition1' => 'outbound_order.document_number',
            'join_condition2' => 'tplus_sale_gross_profit_analysis_summary.outbound_voucher_code',
            'cpid_field' => 'outbound_order.cpid',
            'group_relations' => [
                1 => 'outbound_order.manger_id',
                3 => 'outbound_order.custom_id'
            ]
        ],
        // 销售单数
        5 => [
            'model' => Saleorder::class,
            'relation' => 'sale_order_sub',
            'time_field' => 'sale_order.statistics_at',
            'sum_field' => 'total_count',
            'join_condition1' => 'sale_order_sub.p_id',
            'join_condition2' => 'sale_order.id',
            'cpid_field' => 'sale_order.cpid',
            'group_relations' => [
                1 => 'sale_order.manger_id',
                2 => 'sale_order_sub.steel_factory_name',
                3 => 'sale_order.custom_id',
                4 => 'sale_order_sub.archive_material',
                5 => 'sale_order_sub.archive_spec'
            ]
        ],
        // 基准价格平均值
        6 => [
            'model' => PurchaseSettlePriceLog::class,
            'relation' => null, // 不需要关联其他表
            'time_field' => 'purchase_settle_price_log.create_at',
            'value_field' => 'base_price',
            'sum_field' => 'avg_base_price',
            'cpid_field' => 'purchase_settle_price_log.cpid',
            'conditions' => [
                'type' => 2
            ],
            'aggregation_function' => 'AVG', // 使用 AVG 聚合
            'group_relations' => [] // 不需要分组
        ],
        7 => [
            'model' => PurchaseSettlePriceLog::class,
            'relation' => null, // 不需要关联其他表
            'time_field' => 'purchase_settle_price_log.create_at',
            'value_field' => 'base_price',
            'sum_field' => 'avg_base_price',
            'cpid_field' => 'purchase_settle_price_log.cpid',
            'conditions' => [
                'type' => 3
            ],
            'aggregation_function' => 'AVG', // 使用 AVG 聚合
            'group_relations' => [] // 不需要分组
        ],
        8 => [
            'model' => Saleprice::class,
            'relation' => null, // 不需要关联其他表
            'time_field' => 'sale_price.create_at',
            'value_field' => 'amount',
            'sum_field' => 'avg_amount',
            'cpid_field' => 'sale_price.cpid',
            'conditions' => [
                'type' => 'base'
            ],
            'aggregation_function' => 'AVG', // 使用 AVG 聚合
            'group_relations' => [] // 不需要分组
        ],
        9 => [
            'model' => Saleorder::class,
            'relation' => 'sale_order_sub',
            'time_field' => 'sale_order.statistics_at',
            'sum_field' => 'total_count',
            'join_condition1' => 'sale_order_sub.p_id',
            'join_condition2' => 'sale_order.id',
            'cpid_field' => 'sale_order.cpid',
            'group_relations' => [
                1 => 'sale_order.manger_id',
            ]
        ],
        10 => [
            'model' => PurchaseOrder::class,
            'relation' => 'purchase_order_sub',
            'time_field' => 'purchase_order.create_at',
            'value_field' => 'weight',
            'sum_field' => 'total_weight',
            'join_condition1' => 'purchase_order_sub.order_id',
            'join_condition2' => 'purchase_order.id',
            'cpid_field' => 'purchase_order_sub.cpid',
            'conditions' => [
                'purchase_order_sub.is_del' => 1,
            ],
            'group_relations' => [
                5 => 'purchase_order_sub.manger_id',
            ]
        ],
    ];

    // 同比查询方法
    public static function getListYear($request, $cpid)
    {
        $config = self::getConfig($request->type, $request->data_type);
        $timeRange = self::getTimeRangeYear($request);

        $rdataInfo = self::parseRdata($request->rdata, $request->data_type,$request->type);
        $rdata = $rdataInfo['values'];
        // 构建查询
        list($currentQuery, $lastYearQuery, $keyMap) = self::buildQueries(
            $config,
            $request,
            $cpid,
            $timeRange['current'],
            $timeRange['last'],
        );

        // 数据归一化
        $normalizedData = self::normalizeData(
            $currentQuery,
            $timeRange['range'],
            $config['group_key'],
            $config['sum_field'],
            $request->type,
            $keyMap,
            $rdata // 传入分组键的原始值列表
        );
        $normalizedLastData = self::normalizeData(
            $lastYearQuery,
            $timeRange['range'],
            $config['group_key'],
            $config['sum_field'],
            $request->type,
            $keyMap,
            $rdata, // 传入分组键的原始值列表
            date('Y') - 1
        );

        return self::formatResponse($timeRange['range'], $normalizedData, $normalizedLastData, ['this_year', 'last_year']);
    }

    // 环比查询方法
    public static function getListMonth($request, $cpid)
    {
        $config = self::getConfig($request->type, $request->data_type);
        $timeRange = self::getTimeRangeMonth($request);

        $rdataInfo = self::parseRdata($request->rdata, $request->data_type);
        $rdata = $rdataInfo['values'];
        // 构建查询
        list($currentQuery, $lastMonthQuery, $keyMap) = self::buildQueries(
            $config,
            $request,
            $cpid,
            $timeRange['current'],
            $timeRange['last'],
            null,
            false
        );

        // 数据归一化
        $normalizedData = self::normalizeData(
            $currentQuery,
            $timeRange['range'],
            $config['group_key'],
            $config['sum_field'],
            $request->type,
            $keyMap,
            $rdata,
            null,
            false
        );

        $normalizedLastData = self::normalizeData(
            $lastMonthQuery,
            $timeRange['range'],
            $config['group_key'],
            $config['sum_field'],
            $request->type,
            $keyMap,
            $rdata,
            null,
            false
        );

        return self::formatResponse($timeRange['range'], $normalizedData, $normalizedLastData, ['this_month', 'last_month'],false);
    }

    // 价格走势查询方法
    public static function getPriceTrend($request, $cpid)
    {

        $timeRange = self::getTimeRangePrice($request);

        $data_type = $request->data_type ?? 0;

        if ($data_type == 0) {
            //查询所有数据  销售均价  采购均价 网站价格 操盘定价 期货价格.

            //销售均价 所有销售订单的总金额/所有销售订单的总重量
            // 销售均价 = 销售总金额 / 销售总重量
            $config = self::getConfig($data_type, 9); // 使用销售业绩的配置（weight字段）
//            print_r($config);exit;
            $rdataInfo = self::parseRdata(null, $data_type, $config['type']);

            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];

            $salesAmountQuery = self::buildSingleQuery(
                new Saleorder(),
                array_merge($config, [
                    'value_field' => 'total',
                    'sum_field' => 'total_amount',
                    'aggregation_function' => 'SUM'
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            $salesWeightQuery = self::buildSingleQuery(
                new Saleorder(),
                array_merge($config, [
                    'value_field' => 'total_weight',
                    'sum_field' => 'total_weight',
                    'aggregation_function' => 'SUM'
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            // 合并计算销售均价
            $salesAvgPriceData = self::normalizeAverageData($salesAmountQuery, $salesWeightQuery, $timeRange['range'], $keyMap);

            //采购均价 所有采购订单的总金额/所有采购订单的总重量
            // 采购均价 = 采购总金额 / 采购总重量
            $config = self::getConfig( $data_type,10); // 使用入库量的配置（weight字段）
            $rdataInfo = self::parseRdata(null, $data_type);
            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];

            $purchaseAmountQuery = self::buildSingleQuery(
                new PurchaseOrder(),
                array_merge($config, [
                    'value_field' => 'total_money',
                    'sum_field' => 'total_amount',
                    'aggregation_function' => 'SUM'
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            $purchaseWeightQuery = self::buildSingleQuery(
                new PurchaseOrder(),
                array_merge($config, [
                    'value_field' => 'total_weight',
                    'sum_field' => 'total_weight',
                    'aggregation_function' => 'SUM'
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            // 合并计算采购均价
            $purchaseAvgPriceData = self::normalizeAverageData($purchaseAmountQuery, $purchaseWeightQuery, $timeRange['range'], $keyMap);

            //网站价格 网站价格的平均值
            $config = self::getConfig( $data_type,7);
            $rdataInfo = self::parseRdata(null, $data_type, $config['type']);
            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];

            $WebsitescurrentQuery = self::buildSingleQuery(
                new $config['model'],
                $config,
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            // 数据归一化（仅处理当前数据）
            $WebsitenormalizedData = self::normalizeData(
                $WebsitescurrentQuery,
                $timeRange['range'],
                $config['group_key'],
                $config['sum_field'],
                $request->type,
                $keyMap,
                $rdata
            );

            //操盘定价 销售基价的平均值
            $config = self::getConfig( $data_type,8);

            $rdataInfo = self::parseRdata(null, $data_type, $config['type']);
            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];

            // 查询基价
            $basePriceQuery = self::buildSingleQuery(
                new $config['model'],
                array_merge($config, [
                    'conditions' => [
                        'type' => 'base',
                        'name' => '基价'
                    ]
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid,
                1
            );

            // 查询加减价
            $adjustmentPriceQuery = [];

            // 合并计算均价
            $manipulationpricenormalizedData = self::normalizeDailyPriceData(
                $basePriceQuery,
                $adjustmentPriceQuery,
                $timeRange['day_range']
            );

            //期货价格 期货价格的平均值
            // 构建当前周期查询
            $config = self::getConfig($data_type,6);
            $rdataInfo = self::parseRdata(null, $data_type, $config['type']);
            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];

            $futurespricescurrentQuery = self::buildSingleQuery(
                new $config['model'],
                $config,
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            // 数据归一化（仅处理当前数据）
            $futurespricenormalizedData = self::normalizeData(
                $futurespricescurrentQuery,
                $timeRange['range'],
                $config['group_key'],
                $config['sum_field'],
                $keyMap,
                $rdata
            );
        } elseif ($data_type == 1) {
            // 业务员 - 销售均价 = 销售总金额 / 销售总重量
            $config = self::getConfig( $data_type,9);
            $rdataInfo = self::parseRdata($request->rdata, $data_type);
            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];

            $salesAmountQuery = self::buildSingleQuery(
                new Saleorder(),
                array_merge($config, [
                    'value_field' => 'total',
                    'sum_field' => 'total_amount',
                    'aggregation_function' => 'SUM',
                    'group_key' => 'sale_order.manger_id',
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            $salesWeightQuery = self::buildSingleQuery(
                new Saleorder(),
                array_merge($config, [
                    'value_field' => 'total_weight',
                    'sum_field' => 'total_weight',
                    'aggregation_function' => 'SUM',
                    'group_key' => 'sale_order.manger_id',
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            $salesAvgPriceData = self::normalizeAverageData($salesAmountQuery, $salesWeightQuery, $timeRange['range'], $keyMap);

        } elseif (in_array($data_type, [2, 3, 4])) {
            // 动态设置 type 字段
            $typeMap = [
                2 => 'steel_factory_name',
                3 => 'archive_material',
                4 => 'breed_name'
            ];
            $typeName = $typeMap[$data_type] ?? null;

            // 钢厂 - 操盘定价 = 销售基价的平均值
            $config = self::getConfig($data_type,8);
            $rdataInfo = self::parseRdata($request->rdata, $data_type, $config['type']);
            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];

            // 查询基价
            $basePriceQuery = self::buildSingleQuery(
                new $config['model'],
                array_merge($config, [
                    'conditions' => [
                        'type' => 'base',
                        'name' => '基价'
                    ]
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid,
                1
            );

            // 查询加减价
            $adjustmentPriceQuery = self::buildSingleQuery(
                new $config['model'],
                array_merge($config, [
                    'conditions' => [
                        'type' => $typeName,
                        'name' => current($rdata) // 取第一个值
                    ]
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid,
                1
            );
            // 合并计算均价
            $manipulationpricenormalizedData = self::normalizeDailyPriceData(
                $basePriceQuery,
                $adjustmentPriceQuery,
                $timeRange['day_range']
            );
        } elseif ($data_type == 5) {
            // 采购员 - 采购均价 = 采购总金额 / 采购总重量
            $config = self::getConfig( $data_type,10);
            $rdataInfo = self::parseRdata($request->rdata, 1);
            $rdata = $rdataInfo['values'];
            $keyMap = $rdataInfo['keyMap'];
            $purchaseAmountQuery = self::buildSingleQuery(
                new PurchaseOrder(),
                array_merge($config, [
                    'value_field' => 'total_money',
                    'sum_field' => 'total_amount',
                    'aggregation_function' => 'SUM',
                    'group_key' => 'purchase_order.manger_id',
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            $purchaseWeightQuery = self::buildSingleQuery(
                new PurchaseOrder(),
                array_merge($config, [
                    'value_field' => 'total_weight',
                    'sum_field' => 'total_weight',
                    'aggregation_function' => 'SUM',
                    'group_key' => 'purchase_order.manger_id',
                ]),
                $rdata,
                $timeRange['current'][0],
                $timeRange['current'][1],
                $cpid
            );

            $purchaseAvgPriceData = self::normalizeAverageData($purchaseAmountQuery, $purchaseWeightQuery, $timeRange['range'], $keyMap);

        }


        $data = [];

        if (!empty($salesAvgPriceData)) {
            $data[] = [
                'name' => '销售均价',
                'values' => array_values($salesAvgPriceData['all'])
            ];
        }

        if (!empty($purchaseAvgPriceData)) {
            $data[] = [
                'name' => '采购均价',
                'values' => array_values(self::formatRecursive($purchaseAvgPriceData['all']))
            ];
        }

        if (!empty($WebsitenormalizedData)) {
            $data[] = [
                'name' => '网站价格',
                'values' => array_values(self::formatRecursive($WebsitenormalizedData['all']))
            ];
        }

        if (!empty($manipulationpricenormalizedData)) {
            $data[] = [
                'name' => '操盘定价',
                'values' => array_values(self::formatRecursive($manipulationpricenormalizedData['all']))
            ];
        }


        if (!empty($futurespricenormalizedData)) {
            $data[] = [
                'name' => '期货价格',
                'values' => array_values(self::formatRecursive($futurespricenormalizedData['all']))
            ];
        }

        return self::formatRecursive([
            'time_range' => $timeRange['range'],
            'data' => $data
        ]);

    }

    // 价格走势查询方法-图2
    public static function getPriceTrend2($request, $cpid)
    {

        $timeRange = self::getTimeRangePrice($request);

        $data_type = 0;
//        print_r($keyMap);


        //查询 期现基差=销售均价-操盘录入的期货价格

        //销售均价 所有销售订单的总金额/所有销售订单的总重量
        // 销售均价 = 销售总金额 / 销售总重量
        $config = self::getConfig( $data_type,9); // 使用销售业绩的配置（weight字段）
        $rdataInfo = self::parseRdata($request->rdata, $data_type, $config['type']);
        $rdata = $rdataInfo['values'];
        $keyMap = $rdataInfo['keyMap'];

        $salesAmountQuery = self::buildSingleQuery(
            new Saleorder(),
            array_merge($config, [
                'value_field' => 'total',
                'sum_field' => 'total_amount',
                'aggregation_function' => 'SUM'
            ]),
            $rdata,
            $timeRange['current'][0],
            $timeRange['current'][1],
            $cpid
        );

        $salesWeightQuery = self::buildSingleQuery(
            new Saleorder(),
            array_merge($config, [
                'value_field' => 'total_weight',
                'sum_field' => 'total_weight',
                'aggregation_function' => 'SUM'
            ]),
            $rdata,
            $timeRange['current'][0],
            $timeRange['current'][1],
            $cpid
        );

        // 合并计算销售均价
        $salesAvgPriceData = self::normalizeAverageData($salesAmountQuery, $salesWeightQuery, $timeRange['range'], $keyMap);


        //期货价格 期货价格的平均值
        // 构建当前周期查询
        $config = self::getConfig($data_type,6);
        $rdataInfo = self::parseRdata($request->rdata, $data_type, $config['type']);
        $rdata = $rdataInfo['values'];
        $keyMap = $rdataInfo['keyMap'];

        $futurespricescurrentQuery = self::buildSingleQuery(
            new $config['model'],
            $config,
            $rdata,
            $timeRange['current'][0],
            $timeRange['current'][1],
            $cpid
        );

        // 数据归一化（仅处理当前数据）
        $futurespricenormalizedData = self::normalizeData(
            $futurespricescurrentQuery,
            $timeRange['range'],
            $config['group_key'],
            $config['sum_field'],
            $keyMap,
            $rdata
        );

        // 计算基差
        $basisData = [];
        foreach ($salesAvgPriceData as $key => $values) {
            $basisData[$key] = array_map(function ($date) use ($values, $futurespricenormalizedData, $key) {
                return round($values[$date] - ($futurespricenormalizedData[$key][$date] ?? 0), 2);
            }, array_keys($values));
        }

        return [
            'time_range' => $timeRange['range'],
            'data' => [[
                'name' => '期现基差',
                'values' => array_values($basisData['all'])
            ]]
        ];

    }

    //采购概况
    public static function getPurchaseOverview($request, $cpid)
    {
        //默认获取今日和昨日数据
        //如果有时间区间参数 就查询时间区间的总数居

        //需要获取订货重量，订货金额， 采购订单
        //进货重量，进货金额，    进货单
        //入库重量，入库金额，    入库单
        //采购均额  采购总金额 / 采购总重量
        // 获取时间范围
        $timeRange = self::getTimeRangeForOverview($request);

        // 构建各业务查询
        list($orderData, $orderDataLast) = self::buildOrderQuery($timeRange, $cpid);
        list($inboundData, $inboundDataLast) = self::buildInboundQuery($timeRange, $cpid);
        list($storageData, $storageDataLast) = self::buildStorageQuery($timeRange, $cpid);

        // 统一格式化金额（分转元）
        $orderData = self::formatAmountData($orderData);
        $orderDataLast = self::formatAmountData($orderDataLast);
        $inboundData = self::formatAmountData($inboundData);
        $inboundDataLast = self::formatAmountData($inboundDataLast);
        $storageData = self::formatAmountData($storageData);
        $storageDataLast = self::formatAmountData($storageDataLast);

        // 计算均价
        $currentAvg = $orderData['weight'] > 0
            ? round($orderData['amount'] / $orderData['weight'], 2)
            : 0;

        $lastAvg = $orderDataLast['weight'] > 0
            ? round($orderDataLast['amount'] / $orderDataLast['weight'], 2)
            : 0;
        return  self::formatRecursive([
            // 订货数据及差值
            'orderWeight' => $orderData['weight'] ?? 0,
            'orderAmount' => $orderData['amount'] ?? 0,
            'orderWeightDiff' => self::calculateDiff($orderData['weight'], $orderDataLast['weight']),
            'orderAmountDiff' => self::calculateDiff($orderData['amount'], $orderDataLast['amount']),

            // 进货数据及差值
            'inboundWeight' => $inboundData['weight'] ?? 0,
            'inboundAmount' => $inboundData['amount'] ?? 0,
            'inboundWeightDiff' => self::calculateDiff($inboundData['weight'], $inboundDataLast['weight']),
            'inboundAmountDiff' => self::calculateDiff($inboundData['amount'], $inboundDataLast['amount']),

            // 入库数据及差值
            'storageWeight' => $storageData['weight'] ?? 0,
            'storageAmount' => $storageData['amount'] ?? 0,
            'storageWeightDiff' => self::calculateDiff($storageData['weight'], $storageDataLast['weight']),
            'storageAmountDiff' => self::calculateDiff($storageData['amount'], $storageDataLast['amount']),

            // 均价数据
            'averagePrice' => $currentAvg,
            'averagePriceDiff' => self::calculateDiff($currentAvg, $lastAvg)
        ]);
    }

    //销售概况
    public static function getSaleOverview($request, $cpid)
    {
        //默认获取今日和昨日数据
        //如果有时间区间参数 就查询时间区间的总数居

        //需要获取订货重量，订货金额， 销售订单
        //发货重量，发货金额，    发货单
        //出库重量，出库金额，    出库单
        //销售均额  销售总金额 / 销售总重量
        // 获取时间范围
        $timeRange = self::getTimeRangeForOverview($request);

        // 构建各业务查询
        list($orderData, $orderDataLast) = self::buildSaleOrderQuery($timeRange, $cpid);
        list($inboundData, $inboundDataLast) = self::buildShipmentQuery($timeRange, $cpid);
        list($storageData, $storageDataLast) = self::buildOutboundQuery($timeRange, $cpid);

        // 统一格式化金额（分转元）
        $orderData = self::formatAmountData($orderData);
        $orderDataLast = self::formatAmountData($orderDataLast);
        $inboundData = self::formatAmountData($inboundData);
        $inboundDataLast = self::formatAmountData($inboundDataLast);
        $storageData = self::formatAmountData($storageData);
        $storageDataLast = self::formatAmountData($storageDataLast);

        // 计算均价
        $currentAvg = $orderData['weight'] > 0
            ? round($orderData['amount'] / $orderData['weight'], 2)
            : 0;

        $lastAvg = $orderDataLast['weight'] > 0
            ? round($orderDataLast['amount'] / $orderDataLast['weight'], 2)
            : 0;
        return [
            // 订货数据及差值
            'orderWeight' => $orderData['weight'] ?? 0,
            'orderAmount' => $orderData['amount'] ?? 0,
            'orderWeightDiff' => self::calculateDiff($orderData['weight'], $orderDataLast['weight']),
            'orderAmountDiff' => self::calculateDiff($orderData['amount'], $orderDataLast['amount']),

            // 销货数据及差值
            'inboundWeight' => $inboundData['weight'] ?? 0,
            'inboundAmount' => $inboundData['amount'] ?? 0,
            'inboundWeightDiff' => self::calculateDiff($inboundData['weight'], $inboundDataLast['weight']),
            'inboundAmountDiff' => self::calculateDiff($inboundData['amount'], $inboundDataLast['amount']),

            // 出库数据及差值
            'storageWeight' => $storageData['weight'] ?? 0,
            'storageAmount' => $storageData['amount'] ?? 0,
            'storageWeightDiff' => self::calculateDiff($storageData['weight'], $storageDataLast['weight']),
            'storageAmountDiff' => self::calculateDiff($storageData['amount'], $storageDataLast['amount']),

            // 均价数据
            'averagePrice' => $currentAvg,
            'averagePriceDiff' => self::calculateDiff($currentAvg, $lastAvg)
        ];
    }

    // 核心查询构建方法
    private static function buildQueries($config, $request, $cpid, $currentPeriod, $lastPeriod)
    {
        $rdataInfo = self::parseRdata($request->rdata, $request->data_type,$request->type);
        $rdata = $rdataInfo['values'];
        $keyMap = $rdataInfo['keyMap'];

        $model = new $config['model'];

        // 构建当前周期查询
        $currentQuery = self::buildSingleQuery(
            $model,
            $config,
            $rdata,
            $currentPeriod[0],
            $currentPeriod[1],
            $cpid
        );

        // 构建历史周期查询
        $lastQuery = self::buildSingleQuery(
            $model,
            $config,
            $rdata,
            $lastPeriod[0],
            $lastPeriod[1],
            $cpid
        );

        return [$currentQuery, $lastQuery, $keyMap];
    }

    // 单个查询构建
    private static function buildSingleQuery($model, $config, $rdata, $startTime, $endTime, $cpid, $isday = 0)
    {
        $query = $model::query();

        // JOIN 条件
        if (!empty($config['relation'])) {
            $query->join(
                $config['relation'],
                $config['join_condition1'],
                '=',
                $config['join_condition2']
            );
        }

        // 时间范围
        if (!empty($config['value_field']) && $config['value_field'] === 'amount') { // 仅对 Saleprice 基价查询扩展
            $query->where($config['time_field'], '<=', $endTime);
        } else {
            $query->where($config['time_field'], '>=', $startTime)
                ->where($config['time_field'], '<=', $endTime);
        }

        // CPID 条件
        if ($cpid > 0 && !empty($config['cpid_field'])) {
            $query->where($config['cpid_field'], $cpid);
        }

        //本身的筛选条件
        if (!empty($config['group_key'])) {
            //1业务员2钢厂3客户名称4材质5规格
            $query->whereIn($config['group_key'], $rdata);
        }


        // 额外条件
        if (!empty($config['conditions'])) {
            foreach ($config['conditions'] as $field => $value) {
                $query->where($field, $value);
            }
        }

        // SELECT 和 GROUP BY
        if ($isday) {
            $dateFormat = "FROM_UNIXTIME(huakun_{$config['time_field']}, '%Y-%m-%d') as date";
        } else {
            $dateFormat = "DATE_FORMAT(FROM_UNIXTIME(huakun_{$config['time_field']}), '%Y-%m') as date";
        }

        $selectFields = [DB::raw($dateFormat)];
        if (!empty($config['group_key'])) {
            $selectFields[] = $config['group_key'];
        }

        $aggregationFunction = $config['aggregation_function'] ?? 'SUM';
        $sumField = $config['sum_field'];
        $valueField = $config['value_field'] ?? '';

        // 重量字段转换规则
        $weightFields = ['weight', 'total_weight'];

        // 金额字段转换规则
        $amountFields = ['money','total', 'total_money', 'amount', 'total_amount','gross_profit','performance','base_price'];

        if (in_array($valueField, $weightFields)) {
            if ($aggregationFunction == 'SUM') {
                $selectFields[] = DB::raw("SUM(huakun_{$config['relation']}.{$valueField} / 10000) as {$sumField}");
            } else {
                $selectFields[] = DB::raw("AVG({$valueField} / 10000) as {$sumField}");
            }

        } elseif (in_array($valueField, $amountFields)) {
            if ($aggregationFunction == 'SUM') {
                $selectFields[] = DB::raw("SUM(huakun_{$config['relation']}.{$valueField} / 100) as {$sumField}");
            } else {
                $selectFields[] = DB::raw("AVG({$valueField} / 100) as {$sumField}");
            }
        } elseif (!empty($valueField)){
            if ($aggregationFunction == 'SUM') {
                $selectFields[] = DB::raw("SUM(huakun_{$config['relation']}.{$valueField} ) as {$sumField}");
            } else {
                $selectFields[] = DB::raw("AVG({$valueField} ) as {$sumField}");
            }
        }else{
            $selectFields[] = DB::raw("COUNT('huakun_sale_order.id') as {$sumField}");
        }

        $query->select($selectFields);

        // GROUP BY
        $groupByFields = [DB::raw("DATE_FORMAT(FROM_UNIXTIME(huakun_{$config['time_field']}), '%Y-%m')")];
        if (!empty($config['group_key'])) {
            $groupByFields[] = $config['group_key'];
        }

        foreach ($groupByFields as $field) {
            $query->groupBy($field);
        }
//        $sql = $query->toSql();
//        $bindings = $query->getBindings();

// 输出 SQL 到日志文件
//        Log::info("Constructed SQL: " . $sql, ['bindings' => $bindings]);

        return $query->get()->toArray();
    }

    // 构建采购订单查询（订货数据）
    private static function buildOrderQuery($timeRange, $cpid)
    {
        return self::buildAmountWeightQuery(
            new PurchaseOrder(),
            'purchase_order_sub',
            'purchase_order.create_at',
            $timeRange,
            $cpid,
            'total_weight',
            'total_money',
            'purchase_order.id',   // 主表关联字段
            'purchase_order_sub.order_id',  // 关联表关联字段,
            [
                'purchase_order.is_del' => config('constants.is_del.no'),
            ]
        );
    }

    // 构建进货单查询
    private static function buildInboundQuery($timeRange, $cpid)
    {
        return self::buildAmountWeightQuery(
            new PurchaseStockinOrder(),
            'purchase_stockin_order_sub',
            'purchase_stockin_order.create_at',
            $timeRange,
            $cpid,
            'total_weight',
            'total_money',
            'purchase_stockin_order.id',   // 主表关联字段
            'purchase_stockin_order_sub.stockin_order_id',  // 关联表关联字段,
            [
                'purchase_stockin_order.is_del' => config('constants.is_del.no'),
            ]
        );
    }

    // 构建入库单查询
    private static function buildStorageQuery($timeRange, $cpid)
    {
        return self::buildAmountWeightQuery(
            new PurchaseWarehousingOrder(),
            'purchase_warehousing_order_sub',
            'purchase_warehousing_order.create_at',
            $timeRange,
            $cpid,
            'total_weight',
            'total_money',
            'purchase_warehousing_order.id',   // 主表关联字段
            'purchase_warehousing_order_sub.warehousing_order_id',  // 关联表关联字段,
            [
                'purchase_warehousing_order.is_del' => config('constants.is_del.no'),
                'purchase_warehousing_order.audit_status' => 3
            ]
        );
    }

    // 构建销售订单查询（订货数据）
    private static function buildSaleOrderQuery($timeRange, $cpid)
    {
        return self::buildAmountWeightQuery(
            new Saleorder(),
            'sale_order_sub',
            'sale_order.create_at',
            $timeRange,
            $cpid,
            'total_weight',
            'total',
            'sale_order.id',   // 主表关联字段
            'sale_order_sub.p_id',  // 关联表关联字段,
            [
                'sale_order.is_del'=>config('constants.is_del.no')
            ]
        );
    }

    // 构建出货单查询
    private static function buildShipmentQuery($timeRange, $cpid)
    {
        return self::buildAmountWeightQuery(
            new Salesorder(),
            'sales_order_sub',
            'sales_order.create_at',
            $timeRange,
            $cpid,
            'weight',
            'total',
            'sales_order.id',   // 主表关联字段
            'sales_order_sub.p_id',  // 关联表关联字段,
            [
                'sales_order.is_del'=>config('constants.is_del.no')
            ]
        );
    }

    // 构建出库单查询
    private static function buildOutboundQuery($timeRange, $cpid)
    {
        return self::buildAmountWeightQuery(
            new Outboundorder(),
            'outbound_order_sub',
            'outbound_order.create_at',
            $timeRange,
            $cpid,
            'weight',
            'total',
            'outbound_order.id',   // 主表关联字段
            'outbound_order_sub.p_id',  // 关联表关联字段,
        );
    }

    // 构建金额重量查询
    private static function buildAmountWeightQuery($model, string $relation, string $timeField, array $timeRange, int $cpid, string $weightField = "total_weight", string $moneyField = "total_money", string $joinCurrent = null, string $joinRelation = null, array $conditions = [])
    {
        // 构建当前周期查询
        $current = self::buildBaseQuery($model, $relation, $timeField, $timeRange['current'], $cpid, $joinCurrent, $joinRelation, $conditions)
            ->select(DB::raw("SUM(huakun_{$relation}.{$weightField} / 10000) as weight, SUM(huakun_{$relation}.{$moneyField} / 100) as amount"))
            ->first();

        // 构建环比周期查询
        $last = !empty($timeRange['last'])
            ? self::buildBaseQuery($model, $relation, $timeField, $timeRange['last'], $cpid, $joinCurrent, $joinRelation, $conditions)
                ->select(DB::raw("SUM(huakun_{$relation}.{$weightField} / 10000) as weight, SUM(huakun_{$relation}.{$moneyField} / 100) as amount"))
                ->first()
            : null;

        return [$current, $last];
    }

    //通用查询构建方法
    private static function buildBaseQuery($model, string $relation, string $timeField, array $timeRange, int $cpid, string $joinCurrent = null, string $joinRelation = null, array $conditions = [])
    {
        // 如果未指定关联字段，则使用默认值（保持向后兼容）
        if (!$joinCurrent || !$joinRelation) {
            $joinCurrent = "{$model->getTable()}.id";
            $joinRelation = "{$relation}.order_id";
        }
        return $model::query()
            ->join($relation, $joinRelation, '=', $joinCurrent)
            ->where($timeField, '>=', $timeRange[0])
            ->where($timeField, '<=', $timeRange[1])
            ->when($cpid > 0, function ($query) use ($model, $cpid) {
                return $query->where("{$model->getTable()}.cpid", $cpid);
            })
            ->when(!empty($conditions), function ($query) use ($conditions) {
                foreach ($conditions as $field => $value) {
                    $query->where($field, $value);
                }
                return $query;
            });
    }

    // 获取配置信息
    private static function getConfig(int $type, ?int $dataType = null)
    {
        if (!isset(self::QUERY_CONFIG[$dataType])) {
            throw new \InvalidArgumentException("Invalid report type: {$dataType}");
        }

        $config = self::QUERY_CONFIG[$dataType];

        // 特殊处理 type=6（无分组）
        if (in_array($dataType, [6, 7, 8, 9, 10])) {
            return array_merge($config, [
                'group_key' => null,
                'type' => $type,
                'data_type' => $dataType
            ]);
        }

        // 允许type为空
        if ($type === null || !isset($config['group_relations'][$type])) {
            return array_merge($config, [
                'group_key' => null, // 不使用分组
                'type' => $type,
                'data_type' => $dataType
            ]);
        }

        return array_merge($config, [
            'group_key' => $config['group_relations'][$type],
            'type' => $type,
            'data_type' => $dataType
        ]);
    }

    // 解析rdata
    private static function parseRdata($rdata, $dataType, $type = 1)
    {
        // 特殊处理 type=6（无分组）
        if (in_array($type, [6, 7, 8, 9, 10])) {
            // 统一转为数组处理
            if (is_string($rdata)) {
                $rdata = json_decode($rdata, true);
            }

            if (is_array($rdata) && !isset($rdata['id'])) {
                $rdata = reset($rdata); // 如果是数组，取第一个元素
            }

            if (is_array($rdata) && isset($rdata['id'], $rdata['name'])) {
                return ['values' => [$rdata['name']], 'keyMap' => []];
            }

            return ['values' => ['all'], 'keyMap' => []];
        }

        // 处理 data_type == 0 的情况（无分组）
        if ($dataType == 0) {
            return ['values' => ['all'], 'keyMap' => []];
        }

        if (is_string($rdata)) {
            $rdata = json_decode($rdata, true);
        }

        // 将 rdata 转换为数组（兼容单个对象）
        $items = is_array($rdata)
            ? (isset($rdata['id']) ? [$rdata] : $rdata)
            : [];

        $values = [];
        $keyMap = [];

        foreach ($items as $item) {
            if (!is_array($item)) continue;

            $id = $item['id'] ?? null;
            $name = $item['name'] ?? null;

            if (in_array($type, [1, 3])) {
                if ($id !== null && $name !== null) {
                    $keyMap[$id] = $name;
                    $values[] = $id;
                } elseif ($name !== null) {
                    $values[] = $name;
                }
            } else {
                if ($id !== null && $name !== null) {
                    $keyMap[$id] = $name;
                    $values[] = $name;
                } elseif ($name !== null) {
                    $values[] = $name;
                }
            }

        }
        // 根据 data_type 返回不同的值和映射
        if (in_array($type, [1, 3])) {
            return ['values' => $values ?: ['all'], 'keyMap' => $keyMap];
        } else {
            return ['values' => $values ?: ['all'], 'keyMap' => []];
        }
    }

    // 时间范围计算 - 年同比
    private static function getTimeRangeYear($request)
    {
        $startTime = $request->start_time ?
            strtotime($request->start_time) :
            strtotime(date('Y-01-01'));

        $endTime = $request->end_time ?
            strtotime(date('Y-m-01', strtotime($request->end_time)) . ' +1 month -1 second') :
            strtotime(date('Y-m-01') . ' +1 month -1 second');

        return [
            'current' => [$startTime, $endTime],
            'last' => [strtotime('-1 year', $startTime), strtotime('-1 year', $endTime)],
            'range' => self::generateMonthRange($startTime, $endTime)
        ];
    }

    // 时间范围计算 - 月环比
    private static function getTimeRangeMonth($request)
    {
        $startTime = $request->start_time ?
            strtotime($request->start_time) :
            strtotime(date('Y-m-01'));

        $endTime = $request->start_time ?
            strtotime(date('Y-m-01', strtotime($request->start_time)) . ' +1 month -1 second') :
            strtotime(date('Y-m-01') . ' +1 month -1 second');

        return [
            'current' => [$startTime, $endTime],
            'last' => [strtotime('first day of last month', $startTime),
                strtotime('last day of last month', $startTime)],
            'range' => [date('Y-m', strtotime('first day of last month', $startTime)), date('Y-m', $startTime)]
        ];
    }

    private static function getTimeRangePrice($request)
    {
        // 获取当天结束时间戳（23:59:59）
        $todayEnd = strtotime('tomorrow - 1 second');

        // 获取当前年份的1月1日时间戳
        $currentYearStart = strtotime(date('Y-01-01'));

        // 如果 start_time 为空，默认为今年1月1日
        $startTime = $request->start_time
            ? strtotime($request->start_time)
            : $currentYearStart;

        // 计算 end_time（不超过当天结束时间）
        if ($request->end_time) {
            // 保留原有逻辑，但限制不超过当天
            $endTime = min(
                strtotime(date('Y-m-01', strtotime($request->end_time)) . ' +1 month -1 second'),
                $todayEnd
            );
        } else {
            // 默认值：当前月份最后一天，且不超过当天
            $endTime = min(
                strtotime(date('Y-m-01') . ' +1 month -1 second'),
                $todayEnd
            );
        }
        // 生成按天的时间范围
        $dayRange = self::generateDayRange($startTime, $endTime);

        // 生成按月的 range（用于最终返回）
        $monthRange = self::generateMonthRange($startTime, $endTime);

        return [
            'current' => [$startTime, $endTime],
            'last' => [strtotime('-1 year', $startTime), strtotime('-1 year', $endTime)],
            'range' => $monthRange,
            'day_range' => $dayRange
        ];
    }

    // 新增时间范围处理方法
    private static function getTimeRangeForOverview($request)
    {
        if (!empty($request->start_time) && !empty($request->end_time)) {
            return [
                'current' => [
                    strtotime($request->start_time),
                    strtotime($request->end_time . ' 23:59:59')
                ],
            ];
        }

        // 默认使用今日/昨日
        $todayStart = strtotime(date('Y-m-d'));
        $todayEnd = strtotime('tomorrow - 1 second');

        return [
            'current' => [$todayStart, $todayEnd],
            'last' => [strtotime('yesterday'), strtotime('today - 1 second')]
        ];
    }

    private static function generateDayRange($startTime, $endTime)
    {
        $days = [];
        $current = $startTime;

        while ($current <= $endTime) {
            $days[] = date('Y-m-d', $current);
            $current = strtotime('+1 day', $current);
        }

        return $days;
    }

    // 数据格式化
    private static function formatResponse($timeRange, $currentData, $lastData, $returnkey,$bmonth = true)
    {
        $mergedKeys = array_keys($currentData + $lastData);

        return [
            'time_range' => $timeRange,
            'data' => array_map(function ($key) use ($currentData, $lastData, $timeRange, $returnkey,$bmonth) {
                if($bmonth)
                {
                    $current = $currentData[$key] ?? array_fill_keys($timeRange, 0);
                    $last = $lastData[$key] ?? array_fill_keys($timeRange, 0);
                }else{
                    $current = $currentData[$key] ?? [ 0 ];
                    $last = $lastData[$key] ?? [ 0 ];
                }


                return  self::formatRecursive([
                    'name' => $key,
                    $returnkey[0] => array_values($current),
                    $returnkey[1] => array_values($last)
                ]);
            }, $mergedKeys)
        ];
    }


// 格式化金额数据（分转元）
    private static function formatAmountData($data)
    {
        if (!$data) return ['weight' => 0, 'amount' => 0];

        return [
            'weight' => round($data->weight ?? 0, 4), // weight 保留 4 位小数
            'amount' => round($data->amount ?? 0, 2)  // amount 保留 2 位小数
        ];
    }

    // 生成月份范围
    private static function generateMonthRange($startTime, $endTime)
    {
        $months = [];
        $current = $startTime;

        while ($current <= $endTime) {
            $months[] = date('Y-m', $current);
            $current = strtotime('+1 month', $current);
        }

        return $months;
    }

    // 数据归一化处理
    private static function normalizeData($queryResult, $timeRange, $groupKey, $valueField, $type, $keyMap = [], $values = [],$targetYear = null, $bmonth = true)
    {
        // 无分组，直接归一化为 all
        if ($type == 0 || empty($groupKey)) {
            return self::normalizeDataForAll($queryResult, $timeRange, $valueField);
        }

        $data = [];

        $groupKeyField = explode('.', $groupKey)[1] ?? $groupKey;

        // 替换年份（如果指定了 targetYear）
        $normalizedTimeRange = array_map(function ($date) use ($targetYear) {
            if ($targetYear === null) return $date;
            $month = substr($date, 5); // '2025-01' → '01'
            return "$targetYear-$month";
        }, $timeRange);

        // **Step 1: 初始化所有分组键的时间范围数据为0**
        if($bmonth)
        {
            foreach ($values as $value) {
                $actualKey = is_numeric($value) ? ($keyMap[$value] ?? $value) : $value;
                $data[$actualKey] = array_fill_keys($normalizedTimeRange, 0); // 初始化为0
            }
        }elseif(empty($queryResult)){
            foreach ($values as $value) {
                $actualKey = is_numeric($value) ? ($keyMap[$value] ?? $value) : $value;
                $data[$actualKey] = [ 0 ]; // 默认为0
            }
        }

        foreach ($queryResult as $item) {
            $key = $item[$groupKeyField];
            $actualKey = $keyMap[$key] ?? $key;
            $dateKey = $item['date'];

            if ($targetYear !== null) {
                $month = substr($dateKey, 5);
                $dateKey = "$targetYear-$month";
            }

            if (isset($data[$actualKey][$dateKey]) || !$bmonth) {
                $data[$actualKey][$dateKey] = $item[$valueField];
            }
        }
        // 补全缺失月份数据
        foreach ($data as &$dates) {
            foreach ($normalizedTimeRange as $month) {
                if (!isset($dates[$month]) && $bmonth) {
                    $dates[$month] = 0;
                }
            }
            $dates = array_map([self::class, 'round4'], $dates);
            ksort($dates);
        }

        return $data;
    }

    private static function normalizeDataForAll($queryResult, $timeRange, $valueField)
    {
        $data = ['all' => array_fill_keys($timeRange, 0)];

        foreach ($queryResult as $item) {
            $date = $item['date'];
            $data['all'][$date] = $item[$valueField] ?? 0;
        }

        return $data;
    }

    private static function normalizeAverageData($amountQuery, $weightQuery, $timeRange, $keyMap)
    {
        $result = [];

        $defaultData = array_fill_keys($timeRange, 0);

        // 初始化全局数据结构
        $result['all'] = $defaultData;

        // 填充实际数据
        foreach ($amountQuery as $k => $item) {
            $date = $item['date'];
            $groupKey = 'all';

            $amount = $item['total_amount'] ?? 0;
            if($groupKey == 'all')
            {
                $weight = $weightQuery[$k]['total_weight'] ?? 0;
            }else{
                $weight = $weightQuery[$date][$groupKey]['total_weight'] ?? 0;
            }

            $avg = $weight > 0 ? round($amount / $weight, 2) : 0;

            // 更新对应位置的值
            if(isset($result[$groupKey][$date])) {
                $result[$groupKey][$date] = $avg;
            }
        }

        foreach ($result as &$dates) {
            foreach ($dates as &$value) {
                $value = self::round4($value);
            }
            ksort($dates);
        }

        return $result;
    }

    private static function normalizeDailyPriceData($baseQuery, $adjustmentQuery, $dayRange)
    {
        // Step 1: 构建日期 → 基价映射（全历史）
        $baseMap = [];
        foreach ($baseQuery as $item) {
            if (isset($item['date'])) {
                $baseMap[$item['date']] = $item['avg_amount'] ?? 0;
            }
        }

        // Step 2: 构建日期 → 加减价映射
        $adjustmentMap = [];
        foreach ($adjustmentQuery as $item) {
            if (isset($item['date'])) {
                $adjustmentMap[$item['date']] = $item['avg_amount'] ?? 0;
            }
        }

        // Step 3: 获取所有日期列表（按升序排列）
        $allDates = array_keys($baseMap);
        sort($allDates);

        // Step 4: 按天计算每日价格
        $dailyPrices = [];
        foreach ($dayRange as $day) {
            // 追溯最近有效基价（跨时间范围）
            $base = self::findClosestBasePrice($baseMap, $day, $allDates);
            $adj = $adjustmentMap[$day] ?? 0;

            // op=1 加，op=2 减
            $dailyPrices[$day] = round($base + $adj , 2); // 分 → 元
        }
        // Step 5: 按月归一化
        $monthlyResult = [];
        $currentMonth = '';
        $monthTotal = 0;
        $dayCount = 0;

        // 初始化所有月份为0
        foreach ($dayRange as $day) {
            $month = substr($day, 0, 7); // 'YYYY-MM'
            if (!isset($monthlyResult[$month])) {
                $monthlyResult[$month] = 0;
            }
        }

        foreach ($dailyPrices as $date => $price) {
            $month = substr($date, 0, 7); // 'YYYY-MM'
            if (isset($monthlyResult[$month])) {
                $monthTotal += $price;
                $dayCount++;
            }
        }

        // 重新计算平均值
        foreach ($monthlyResult as $month => $value) {
            $matchingDays = array_filter(array_keys($dailyPrices), function($date) use ($month) {
                return substr($date, 0, 7) === $month;
            });

            if (!empty($baseMap)) {
                $firstValidDate = min(array_keys($baseMap));
                $validDays = array_filter($matchingDays, function($date) use ($firstValidDate) {
                    return $date >= $firstValidDate;
                });

                // 使用有效日期计算平均值
                if (!empty($validDays)) {
                    $sum = array_sum(array_intersect_key($dailyPrices, array_flip($validDays)));
                    $monthlyResult[$month] = round($sum / count($validDays), 2);
                } else {
                    $monthlyResult[$month] = 0; // 没有有效日期则保持0
                }
            } else {
                // 无基价数据时保持0
                $monthlyResult[$month] = 0;
            }
        }

        return ['all' => $monthlyResult];

    }

    private static function findClosestBasePrice($baseMap, $date, $allDates)
    {
        // Step 0: 如果没有基价数据直接返回0
        if (empty($baseMap)) {
            return 0;
        }

        // Step 1: 获取有效数据范围边界
        $firstDate = min(array_keys($baseMap)); // 最早的有效数据日期

        // Step 2: 如果查询日期早于第一条有效数据日期，直接返回0
        if ($date < $firstDate) {
            return 0;
        }

        // Step 3: 检查当前日期是否有直接数据
        if (isset($baseMap[$date])) {
            return $baseMap[$date];
        }

        // Step 4: 向前查找最近的有效数据（限制在有效时间范围内）
        $index = array_search($date, $allDates);
        for ($i = $index - 1; $i >= 0; $i--) {
            $prevDate = $allDates[$i];
            // 当前查找日期早于第一条有效数据时停止查找
            if ($prevDate < $firstDate) break;
            // 找到有效数据则返回
            if (isset($baseMap[$prevDate])) {
                return $baseMap[$prevDate];
            }
        }

        // Step 6: 如果当前时间范围无有效基价，取全局最近一条
        krsort($baseMap);
        return reset($baseMap) ?: 0;
    }


    // 新增差值计算方法
    private static function calculateDiff($current, $last)
    {
        return $current !== null && $last !== null
            ? self::round4($current - $last)
            : 0;
    }

    /**
     * 递归格式化嵌套数组中的数值
     */
    private static function formatRecursive($data)
    {
        if (is_array($data)) {
            foreach ($data as &$item) {
                $item = self::formatRecursive($item);
            }
            return $data;
        } elseif (is_numeric($data)) {
            return self::round4($data);
        }
        return $data;
    }

    /**
     * 保留4位有效数字（四舍五入）
     */
    private static function round4($value)
    {
        return round((float)$value, 4);
    }
}
